from django.shortcuts import render

# Create your views here.
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from oauth.models import OpenidUserModel
from oauth.serializers import QQAuthUserSerializer
from oauth.utils import OAuthQQ


class OAuthView(APIView):
    # 第一步 前段get请求 后端返回可以扣扣登陆的网页url
    # /oauth/qq/authorization/?next=xxx
    # 后端需要获得next的数据以拼接出前段需要的扣扣登陆URL
    def get(self, request):
        next_url = request.query_params.get('next', '/')
        oauth = OAuthQQ(state=next_url)
        url = oauth.get_oauth_url()

        return Response({
            'login_url': url
        })


# 请求方式 ： GET /oauth/qq/user/?code=xxx
class QQAuthUserView(CreateAPIView):

    serializer_class = QQAuthUserSerializer

    # # 第二步 接受前段传过来的code 并且通过code去拿openid
    def get(self, request):
        # 取出code
        code = request.query_params.get('code')

        # 通过code去找第三方要access_token
        oauth = OAuthQQ()
        access_token = oauth.get_access_token(code)

        # 通过access_token去取出openid
        openid = oauth.get_openid(access_token)

        # 判断该用户是否已经绑定
        try:
            qq_user = OpenidUserModel.objects.get(openid=openid)
        except OpenidUserModel.DoesNotExist:
            token = oauth.generate_save_user_token(openid)
            return Response({'access_token': token})
        else:
            user = qq_user.user
            # 补充生成记录登录状态的token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            user.token = token

            return Response({'token': token,
                             'user_id': user.id,
                             'username': user.username})


    # 第三步 请求方式： POST /oauth/qq/user/

